package com.itheima.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/cookie/demo04")
public class ServletDemo04 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //直接给cookie
        Cookie cookie = new Cookie("time4",System.currentTimeMillis()+"");
        cookie.setMaxAge(0);

        resp.addCookie(cookie);

        //在页面上响应数据
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("欢迎登陆本系统,您上一次的访问时间是:<br>");

        Cookie[] cookies = req.getCookies();
        if (cookies!=null) {
            for (Cookie cookie1 : cookies) {
                if("time4".equals(cookie1.getName())){
                    long l = Long.parseLong(cookie1.getValue());
                    Date date = new Date(l);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = sdf.format(date);
                    writer.write(format);
                }
            }
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
